package com.h3c.nem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.h3c.nem.dto.*;
import com.h3c.nem.entity.SdAllWorker;
import com.h3c.nem.entity.TbApprovalRecord;
import com.h3c.nem.entity.TbTrainClass;
import com.h3c.nem.entity.TbTrainWorker;
import com.h3c.nem.mapper.TbApprovalRecordMapper;
import com.h3c.nem.mapper.TbTrainClassMapper;
import com.h3c.nem.mapper.TbTrainWorkerMapper;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ITbTrainClassService;
import com.h3c.nem.service.ITbTrainWorkerService;
import com.h3c.nem.utils.BusiEnumDefine;
import org.springframework.beans.BeanUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: TbTrainClassServiceImpl
 *
 * @Author: j26296
 * @Date: 2022-06-20
 * Description: tb_train_class serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TbTrainClassServiceImpl extends ServiceImpl<TbTrainClassMapper, TbTrainClass> implements ITbTrainClassService {

    @Resource
    private TbTrainClassMapper tbTrainClassMapper;
    @Resource
    private TbTrainWorkerMapper tbTrainWorkerMapper;
    @Resource
    private TbApprovalRecordMapper tbApprovalRecordMapper;
    @Autowired
    private CommService commService;
    @Autowired
    private ITbTrainWorkerService tbTrainWorkerService;
    @Autowired
    private ITbTrainClassService tbTrainClassService;

    /**
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-06-20
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public List<TbTrainClassDTO> selectFuzzyByDto(TbTrainClassDTO dto) {
        List<TbTrainClass> list = tbTrainClassMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto),TbTrainClass.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), TbTrainClassDTO.class);
    }

    /**
     * @title: selectByDto
     * @description: 精确查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-06-20
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public List<TbTrainClassDTO> selectByDto(TbTrainClassDTO dto) {
        List<TbTrainClass> list = tbTrainClassMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto),TbTrainClass.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), TbTrainClassDTO.class);
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-06-20
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer insertDto(TbTrainClassDTO dto) {
        //if (null == dto.getId() || "".equals(dto.getId())) {
        //    String pkId = IdWorker.nextId() + "";
        //    dto.setId(pkId);
        //}
        return tbTrainClassMapper.insertTbTrainClass(JSONObject.parseObject(JSON.toJSONString(dto), TbTrainClass.class));
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-06-20
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer updateDto(TbTrainClassDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        return tbTrainClassMapper.updateTbTrainClass(JSONObject.parseObject(JSON.toJSONString(dto), TbTrainClass.class));
        //return tbTrainClassMapper.updateByPrimaryKey(JSONObject.parseObject(JSON.toJSONString(dto), TbTrainClass.class));
        //} else {
        //    return 0;
        //}
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-06-20
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer deleteDto(TbTrainClassDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        return tbTrainClassMapper.deleteTbTrainClass(JSONObject.parseObject(JSON.toJSONString(dto), TbTrainClass.class));
        //return tbTrainClassMapper.deleteByPrimaryKey(dto.getId());
        //} else {
        //    return 0;
        //}
    }

    /*
     * psa调用，传入一个班级，包含学员信息
     * 保存至本地班级，学员表；发送待办
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<PsaTbTrainWorkerDTO> syncPsaAndSendOneMail(PsaTbTrainClassDTO data){
        //该班级已有的人
        List<TbTrainWorker> tbTrainWorkerEx = tbTrainWorkerMapper.selectList(new QueryWrapper<TbTrainWorker>()
                .eq("class_id",data.getClassId()));
        List<String> workerIds = tbTrainWorkerEx.stream().map(TbTrainWorker::getWorkerId).collect(Collectors.toList());

        TbTrainClass tbTrainClass = new TbTrainClass();
        BeanUtils.copyProperties(data,tbTrainClass);
//        tbTrainClass.setClassId(data.getClassId());
//        tbTrainClass.setClassName(data.getClassName());
//        tbTrainClass.setBeginDate(data.getBeginDate());
//        tbTrainClass.setEndDate(data.getEndDate());

        SdAllWorker sdAllWorker = commService.getAllWorkerDoFromLocalCache(data.getCreatorId());
        if(sdAllWorker==null){
            tbTrainClass.setCreatorInfo(data.getCreatorId());
        }else{
            tbTrainClass.setCreatorInfo(sdAllWorker.getWorkerName()+"/"+data.getCreatorId());
        }
        SdAllWorker teacher = commService.getAllWorkerDoFromLocalCache(data.getMainTeacherId());
        tbTrainClass.setMainTeacher(teacher.getWorkerName()+"/"+data.getMainTeacherId());
        tbTrainClass.setSyncTime(new Date());

        tbTrainClassService.saveOrUpdate(tbTrainClass);

        //该班级已经创建过待办的学员
        List<String> recordWorkerIds = new ArrayList<>();
        List<TbApprovalRecord> tbApprovalRecords = tbApprovalRecordMapper.selectList(new QueryWrapper<TbApprovalRecord>()
                .eq("approval_note",data.getClassId()));
        recordWorkerIds = tbApprovalRecords.stream().map(TbApprovalRecord::getApprovalUserId).collect(Collectors.toList());


        List<Map<String,Object>> psaTrainWorkerDatas = (List<Map<String,Object>>)data.getTraineeList();
        List<TbTrainWorker> tbTrainWorkers = new ArrayList<>();
        List<PsaTbTrainWorkerDTO> psaTbTrainWorkerDTOS = new ArrayList<>();
        for (Map<String,Object> psaTrainWorkerData : psaTrainWorkerDatas) {
            TbTrainWorker tbTrainWorker = new TbTrainWorker();
            tbTrainWorker.setClassId(data.getClassId());
            tbTrainWorker.setWorkerId((String) psaTrainWorkerData.get("empNo"));
            SdAllWorker sdAllWorker1 = commService.getAllWorkerDoFromLocalCache((String) psaTrainWorkerData.get("empNo"));
            tbTrainWorker.setWorkerName(sdAllWorker1.getWorkerName());
            tbTrainWorker.setDataSource(1);

            if(Objects.equals(psaTrainWorkerData.get("letterIsPushNeed"), "是")){
                tbTrainWorker.setPushLetterFlag(1);
            }else {
                tbTrainWorker.setPushLetterFlag(2);
            }

            //不需要写邮件的letterStatus:待启动
            if(Objects.equals(psaTrainWorkerData.get("letterIsWriteNeed"), "是")){
                tbTrainWorker.setWriteLetterFlag(1);
                tbTrainWorker.setLetterStatus(BusiEnumDefine.ONE_MAIL_STATUS_WRITING);
            }else {
                tbTrainWorker.setWriteLetterFlag(2);
                tbTrainWorker.setLetterStatus(BusiEnumDefine.ONE_MAIL_STATUS_WAITING);
            }
            if(workerIds.contains(tbTrainWorker.getWorkerId())){
                tbTrainWorkerService.update(tbTrainWorker,new QueryWrapper<TbTrainWorker>()
                        .eq("class_id",tbTrainWorker.getClassId())
                        .eq("worker_id",tbTrainWorker.getWorkerId())
                );
            }else {
                tbTrainWorkerMapper.insert(tbTrainWorker);
                workerIds.add(tbTrainWorker.getWorkerId());
            }

            //需要启动一封信的才发送待办
            if(tbTrainWorker.getWriteLetterFlag()==1&&(recordWorkerIds.size()==0||!recordWorkerIds.contains(tbTrainWorker.getWorkerId()))){
                tbTrainWorkers.add(tbTrainWorker);
                recordWorkerIds.add(tbTrainWorker.getWorkerId());

                PsaTbTrainWorkerDTO psaTbTrainWorkerDTO = new PsaTbTrainWorkerDTO();
                BeanUtils.copyProperties(tbTrainWorker,psaTbTrainWorkerDTO);
                psaTbTrainWorkerDTO.setLetterStatusCN(BusiEnumDefine.ONE_MAIL_STATUS_WRITINGCN);
                if(psaTbTrainWorkerDTO.getPushLetterFlag()==1){
                    psaTbTrainWorkerDTO.setLetterIsPushNeed("是");
                }else {
                    psaTbTrainWorkerDTO.setLetterIsPushNeed("否");
                }
                if(psaTbTrainWorkerDTO.getWriteLetterFlag()==1){
                    psaTbTrainWorkerDTO.setLetterIsWriteNeed("是");
                }else{
                    psaTbTrainWorkerDTO.setLetterIsWriteNeed("否");
                }
                psaTbTrainWorkerDTO.setLetterTitle("");
                psaTbTrainWorkerDTO.setLetterContent("");
                psaTbTrainWorkerDTOS.add(psaTbTrainWorkerDTO);

            }
        }
        //创建待办
        tbTrainWorkerService.sendOneMail(tbTrainWorkers,data.getClassId());
        return psaTbTrainWorkerDTOS;
    }

}
